<template>
  <view class="image-favorite">
    <button 
      class="favorite-btn" 
      :class="{ favorited: isFavorited }"
      @click="toggleFavorite"
      :loading="isLoading"
    >
      <text class="favorite-icon">{{ isFavorited ? '❤️' : '🤍' }}</text>
    </button>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue'
import { toggleImageFavorite } from '@/services/api/backendApi'

// 组件属性
const props = defineProps({
  // 图片ID
  imageId: {
    type: String,
    required: true
  },
  // 初始收藏状态
  initialFavorite: {
    type: Boolean,
    default: false
  }
})

// 组件事件
const emit = defineEmits(['favorite-changed'])

// 响应式数据
const isFavorited = ref(props.initialFavorite)
const isLoading = ref(false)

// 监听初始状态变化
watch(() => props.initialFavorite, (newVal) => {
  isFavorited.value = newVal
})

// 方法
const toggleFavorite = async () => {
  if (isLoading.value) return
  
  try {
    isLoading.value = true
    
    const newFavoriteStatus = !isFavorited.value
    await toggleImageFavorite(props.imageId, newFavoriteStatus ? 1 : 0)
    
    isFavorited.value = newFavoriteStatus
    
    // 触发父组件事件
    emit('favorite-changed', {
      imageId: props.imageId,
      isFavorited: newFavoriteStatus
    })
    
    uni.showToast({
      title: newFavoriteStatus ? '收藏成功' : '取消收藏',
      icon: 'success'
    })
    
  } catch (error) {
    console.error('收藏操作失败:', error)
    
    // 如果API未实现（404错误），使用本地模拟
    if (error.message && error.message.includes('404')) {
      console.log('收藏API未实现，使用本地模拟')
      
      const newFavoriteStatus = !isFavorited.value
      isFavorited.value = newFavoriteStatus
      
      // 触发父组件事件
      emit('favorite-changed', {
        imageId: props.imageId,
        isFavorited: newFavoriteStatus
      })
      
      uni.showToast({
        title: newFavoriteStatus ? '收藏成功（本地）' : '取消收藏（本地）',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  } finally {
    isLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.image-favorite {
  display: flex;
  justify-content: center;
  align-items: center;
}

.favorite-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border: 2px solid #e0e0e0;
  border-radius: 50%;
  background: #fff;
  transition: all 0.3s ease;
  cursor: pointer;
  font-family: 'Fugaz One', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  
  &:hover {
    border-color: #ff6b6b;
    background: #fff5f5;
  }
  
  &.favorited {
    border-color: #ff6b6b;
    background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
    color: #fff;
    
    &:hover {
      background: linear-gradient(135deg, #ff5252, #ff7979);
    }
  }
  
  &:active {
    transform: scale(0.9);
  }
  
  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    
    &:active {
      transform: none;
    }
  }
}

.favorite-icon {
  font-size: 20px;
  line-height: 1;
}
</style>
